package com.ykt.controller;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.JFinal;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.ext.route.ControllerBind;
import com.ykt.content.Content;
import com.ykt.interceptor.LoginAdminInterceptor;
import com.ykt.model.Admin;
import com.ykt.model.LoginLog;
import com.ykt.model.Menu;
import com.ykt.vo.page.LoginInfo;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings({"unchecked", "rawtypes"})
@ControllerBind(controllerKey = "/", viewPath = "/common")
public class HomeController extends BaseController {
    /**
     * 存储已经登录的用户 map<ip,LoginInfo>
     */
    public static Map<String, LoginInfo> loginUser = new HashMap<String, LoginInfo>();

    public HomeController() {
        super(null);
    }

    @Clear
    public void index() {
        Admin admin = getCurrentUser();
        
//        String root = JFinal.me().getContextPath();
//        this.setAttr("root", root);
        
        if (admin == null)
            render("/common/login.html");
        else
            render("/common/index.html");
    }

    @Clear
    public void login() {
        String username = getPara("username");
        String password = getPara("password");
        Admin admin = Admin.dao.checkUser(username, password);
        if (admin == null) {
            this.rendJson(false, "用户名密码不正确");
            return;
        }
        int userId = admin.getInt("id");
        boolean single = true;//是否控制登录
        if (single) {
            if (loginUser.size() > 0)
                for (String key : loginUser.keySet()) {
                    LoginInfo loginInfo = loginUser.get(key);
                    try {
                        Integer uid_ = loginInfo.getUserId();
                        if (uid_ != null && uid_ == admin.getInt("id")) {
                            loginUser.remove(key);
                        }
                    } catch (Exception e) {
                        loginUser.remove(key);
                    }
                }
        }
        String ip = this.getRequest().getHeader("X-Real-IP");
        Date time = new Date();
        if (ip == null) {
            ip = this.getRequest().getRemoteAddr();
        }
        LoginLog loginLog = new LoginLog();
        loginLog.set("ip", ip);
        loginLog.set("user_id", userId);
        loginLog.set("login_time", time);
        loginLog.save();

        loginUser.put(ip, new LoginInfo(ip, admin.getInt("id"), time));


        this.setCookie(Content.SESSION_LOGIN_LOG_ID, loginLog.getLong("id").toString(), 60 * 12);//12小时
        setSessionAttr(Content.SESSION_LOGIN_USER, admin);

        //CacheKit.removeAll("authority");//登录的时候 删除所有权限缓存
        this.rendJson(true, "登录成功");
    }

    @Clear
    @Before(SessionInViewInterceptor.class)
    public void north() {
        render("/common/north.html");
    }

    @Clear
    @Before(LoginAdminInterceptor.class)
    public void west() {

        Admin admin = getCurrentUser();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        for (Menu pm : admin.getMenu()) {

            Map<String, Object> mMap = pm.getAttrMaps();//将model转换成map
            mMap.put("slist", admin.getMenuSub(pm.getInt("id")));//然后把子菜单放入到map里面
            mapList.add(mMap);
        }
        setAttr("menuList", mapList);
        render("/common/west.html");
    }

    @Clear
    public void logout() {
        String sessionId = this.getRequest().getSession().getId();
        loginUser.remove(sessionId);
        String loginLogId = this.getCookie(Content.SESSION_LOGIN_LOG_ID);
        if (loginLogId != null && !"".equals(loginLogId)) {
            LoginLog.dao.findById(loginLogId).set("logout_time", new Date()).update();
        }
        this.removeCookie(Content.SESSION_LOGIN_LOG_ID);
        this.removeSessionAttr(Content.SESSION_LOGIN_USER);
        this.redirect("/");
    }
}
